//
//  UIUTils.m
//  niupipi
//
//  Created by mac on 16/2/25.
//  Copyright © 2016年 zhanlijun. All rights reserved.
//

#import "UIUTils.h"
#import "MBProgressHUD.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <Photos/Photos.h>

@implementation UIUTils
+ (CGFloat)getWindowWidth
{
    UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];
    return mainWindow.frame.size.width;
}

+ (CGFloat)getWindowHeight
{
    UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];
    return mainWindow.frame.size.height;
}


+ (BOOL)isBlankString:(NSString *)str
{
    NSString *string = [NSString stringWithFormat:@"%@",str];
    if (string == nil) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    if ([string isEqualToString:@"<null>"]) {
        return YES;
    }
    if (string == NULL) {
        return YES;
    }
    if ([string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length==0) {
        return YES;
    }
    
    return NO;
}


//时间戳转换成当前时区的日期
+ (NSString *)getDateFromDateLine:(NSString *)dateLine format:(NSString *)format
{
    //上传时的时间戳（格林尼治时间戳）
    NSString *timeIntervalSince1970 = dateLine;
    //把时间戳转换成日期（格林尼治日期）
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeIntervalSince1970 intValue]];
    //初始化时间格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //给时间格式设置时区（中国 东八区时区）
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [dateFormatter setTimeZone:timeZone];
    //给时间格式设置格式参数
    //YYYY:MM:dd-HH:mm:ss
    [dateFormatter setDateFormat:format];
    
    //获取date对应dateFormatter格式的字符串（中国 东八区日期）
    NSString *timeString = [dateFormatter stringFromDate:date];
    return timeString;
}

+ (UIColor *)colorFromHexCode:(NSString *)hexString {
    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    if([cleanString length] == 3) {
        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
    }
    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }
    
    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
    
    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;
    float alpha = ((baseValue >> 0) & 0xFF)/255.0f;
    
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
//生成纯色图片
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//计算文本高度
+ (CGFloat)getTextHeight:(NSString *)text width:(CGFloat)width font:(UIFont *)font
{
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return textRect.size.height;
}
#pragma mark MBProgressHUD

+ (void)showActivityMBProgressHUDWithTitle:(NSString *)title view:(UIView *)view
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = title;
}

+ (void)removeActivityMBProgressHUDWithView:(UIView *)view
{
    [view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[MBProgressHUD class]]) {
            [obj hide:YES];
            
            [obj removeFromSuperview];
        }
    }];
}

+ (void)showReminderMBProgressHUDWithTitle:(NSString *)title view:(UIView *)view
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:HUD];
    HUD.labelText = title;
    HUD.mode = MBProgressHUDModeText;
    
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    //    HUD.yOffset = 150.0f;
    //    HUD.xOffset = 100.0f;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];
}
+(BOOL)iscanUseCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        AVAuthorizationStatus author = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (author == AVAuthorizationStatusRestricted || author == AVAuthorizationStatusDenied) {
            //展示相机权限的提示
            
            NSString *titleString = [NSString stringWithFormat:@"请在%@的“设置－隐私－相机”选项中，允许访问您的手机。",[UIDevice currentDevice].model];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titleString message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
            [alertView show];
            
            return NO;
            
        } else {
            //展示相机
            return YES;
            
        }
    }
    else{
        
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"您的设备不具备拍照功能" message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [alertView show];
        return NO;
    }

}

//访问相册
+ (BOOL)iscanvisitLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        //判断系统版本大于等于8.0
        if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
            //系统版本为8.0及以上时 用来判断相册权限是否打开的方法
            PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
            if (author==PHAuthorizationStatusRestricted||author==PHAuthorizationStatusDenied) {
                
                NSLog(@"系统版本为8.0及以上 关闭了相册");
                //展示相册权限的提示
                NSString *titleString = [NSString stringWithFormat:@"请在%@的“设置－隐私－%@”选项中，允许新手阅读访问您的手机。",[UIDevice currentDevice].model,@"照片"];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titleString message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                [alertView show];
                return NO;
                
            } else {
                
                //展示相册
                return YES;
                
            }
        } else {
            //系统版本为8.0之前 用来判断相册权限是否打开的方法
            ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
            if (author==ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
                
                NSLog(@"系统版本为8.0之前 关闭了相册");
                //展示相册权限的提示
                NSString *titleString = [NSString stringWithFormat:@"请在%@的“设置－隐私－%@”选项中，允许新手阅读访问您的手机。",[UIDevice currentDevice].model,@"照片"];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titleString message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                [alertView show];
                return NO;
                
            } else {
                
                //展示相册
                return  YES;
                
            }
        }
    } else {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"未找到您的相册" message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [alertView show];
        return NO;
    }
}


+(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
    
}

+ (BOOL)isPhoneNumber:(NSString *)number
{
    NSString *phoneRegex1=@"1[34578]([0-9]){9}";
    NSPredicate *phoneTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex1];
    return  [phoneTest1 evaluateWithObject:number];
}

+(NSString *)getStringWithleng:(int)leng
{
    char data[leng];
    for (int x=0;x<leng;data[x++] = (char)('A' + (arc4random_uniform(26))));
    return [[NSString alloc] initWithBytes:data length:leng encoding:NSUTF8StringEncoding];
}

@end
